package com.smartleanx.module.hrm.service.salary;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartleanx.framework.tenant.core.context.TenantContextHolder;
import com.smartleanx.module.hrm.dal.dataobject.dingDing.DingAttendanceTeam;
import com.smartleanx.module.hrm.dal.dataobject.dingDing.SystemAttendanceTeam;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.mysql.dingDing.DingAttendanceTeamMapper;
import com.smartleanx.module.hrm.dal.mysql.dingDing.SystemAttendanceTeamMapper;
import com.smartleanx.module.hrm.dal.mysql.dingDing.SystemAttendanceTeamMapper;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import com.smartleanx.module.hrm.service.examine.util.exception.ResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2025-02-10
 */
@Service
public class SystemAttendanceTeamServiceImpl implements SystemAttendanceTeamService {
    @Autowired
    private SystemAttendanceTeamMapper systemAttendanceTeamMapper;
    @Autowired
    private EmployeeService employeeService;

    @Override
    public PageInfo<SystemAttendanceTeam> selectPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SystemAttendanceTeam> dingAttendanceTeams = systemAttendanceTeamMapper.selectList(null);
        dingAttendanceTeams = dingAttendanceTeams.stream().peek(p -> {
            p.setAdaptPersonNameList(StrUtil.splitTrim(p.getAdaptPersonName(), ","));

        }).collect(Collectors.toList());
        return new PageInfo<>(dingAttendanceTeams);
    }

    @Override
    public SystemAttendanceTeam selectOne(Integer teamId) {
        SystemAttendanceTeam attendanceTeam = systemAttendanceTeamMapper.selectById(teamId);
        if (ObjectUtils.isEmpty(attendanceTeam)) {
            throw new ResultException("考勤信息不存在请刷新后重试");
        }
        if(StrUtil.isNotBlank(attendanceTeam.getAdaptPersonUser())){
            attendanceTeam.setAdaptPersonUserList(StrUtil.splitTrim(attendanceTeam.getAdaptPersonUser(), ","));
        }
        return attendanceTeam;
    }


    @Override
    public void updateDeductionRule(SystemAttendanceTeam attendanceTeam) {
        if (attendanceTeam.getId() == null) {
            throw new ResultException("考勤组不能为空");
        }


        if(CollUtil.isNotEmpty(attendanceTeam.getAdaptPersonUserList())){
            //1. 用户id 字符串   比如 1,2,3
            List<String> strings = StrUtil.splitTrim(attendanceTeam.getAdaptPersonUser(), ",");

            Long tenantId = TenantContextHolder.getTenantId();
            List<SystemAttendanceTeam> attendanceTeamList = systemAttendanceTeamMapper.selectList(new LambdaQueryWrapper<SystemAttendanceTeam>()
                    .eq(SystemAttendanceTeam::getTenantId, tenantId)
                    .ne(SystemAttendanceTeam::getId,attendanceTeam.getId())
            );
            attendanceTeam.setAdaptPersonUserList(strings);

            //2. 查询员工
            List<EmployeeDO> employeeList = employeeService.getEmployeeByUserIds(attendanceTeam.getAdaptPersonUserList().stream().map(Long::new).collect(Collectors.toSet()));

            //2.1 获取已经有考勤组的用户id
            List<Long> ids = strings.stream().filter(p -> attendanceTeamList.stream().filter(attendanceTeamItem -> null!= attendanceTeamItem.getAdaptPersonUser() && attendanceTeamItem.getAdaptPersonUser().contains(p)).findAny().orElse(null) != null).map(Long::new).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(ids)){
                Map<Long, String> map = employeeList.stream().collect(Collectors.toMap(EmployeeDO::getUserId, EmployeeDO::getName));
                StringBuilder string = new StringBuilder();
                for (int i = 0; i < ids.size(); i++) {
                    string.append(map.get(ids.get(i)));
                    if(i != ids.size() -1){
                        string.append("、");
                    }
                }
                throw new ResultException(string.toString()+"已有考勤组");
            }

            String collect = employeeList.stream().map(EmployeeDO::getId).map(Object::toString).collect(Collectors.joining(","));
            attendanceTeam.setAdaptPerson("," + collect + ",");

            //3. 讲员工名字保存到数据库 以字符串形式  比如 张三,李四,王五
            String names = employeeList.stream().map(EmployeeDO::getName).collect(Collectors.joining(","));
            attendanceTeam.setAdaptPersonName(names);
        }else{
            attendanceTeam.setAdaptPerson(null);
        }

        systemAttendanceTeamMapper.updateById(attendanceTeam);
    }

    @Override
    public void saveDeductionRule(SystemAttendanceTeam attendanceTeam) {
        //1. 用户id 字符串   比如 1,2,3
        List<String> strings = StrUtil.splitTrim(attendanceTeam.getAdaptPersonUser(), ",");
        attendanceTeam.setAdaptPersonUserList(strings);
        Long tenantId = TenantContextHolder.getTenantId();
        List<SystemAttendanceTeam> attendanceTeamList = systemAttendanceTeamMapper.selectList(new LambdaQueryWrapper<SystemAttendanceTeam>()
                .eq(SystemAttendanceTeam::getTenantId, tenantId)
        );

        //2. 查询员工
        List<EmployeeDO> employeeList = employeeService.getEmployeeByUserIds(attendanceTeam.getAdaptPersonUserList().stream().map(Long::new).collect(Collectors.toSet()));

        //2.1 获取已经有考勤组的用户id
        List<Long> ids = strings.stream().filter(p -> attendanceTeamList.stream().filter(attendanceTeamItem -> null!= attendanceTeamItem.getAdaptPersonUser() && attendanceTeamItem.getAdaptPersonUser().contains(p)).findAny().orElse(null) != null).map(Long::new).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(ids)){
            Map<Long, String> map = employeeList.stream().collect(Collectors.toMap(EmployeeDO::getUserId, EmployeeDO::getName));
            StringBuilder string = new StringBuilder();
            for (int i = 0; i < ids.size(); i++) {
                string.append(map.get(ids.get(i)));
                if(i != ids.size() -1){
                    string.append("、");
                }
            }
            throw new ResultException(string.toString()+"已有考勤组");
        }
        String collect = employeeList.stream().map(EmployeeDO::getId).map(Object::toString).collect(Collectors.joining(","));
        attendanceTeam.setAdaptPerson("," + collect + ",");

        //3. 讲员工名字保存到数据库 以字符串形式  比如 张三,李四,王五
        String names = employeeList.stream().map(EmployeeDO::getName).collect(Collectors.joining(","));
        attendanceTeam.setAdaptPersonName(names);
        systemAttendanceTeamMapper.insert(attendanceTeam);
    }

    @Override
    public void removeDeductionRule(Integer id) {
        SystemAttendanceTeam systemAttendanceTeam = systemAttendanceTeamMapper.selectById(id);
        if(StrUtil.isNotBlank(systemAttendanceTeam.getAdaptPerson())){
            throw new ResultException("考勤组含有适用人员，不可删除");
        }

        systemAttendanceTeamMapper.deleteById(id);
    }

}
